package io.renren.modules.work.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import io.renren.common.utils.ExcelListener;
import io.renren.common.utils.R;

import io.renren.modules.work.entity.ExcelData_Goods;
import org.apache.commons.lang.StringUtils;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.work.dao.ScGoodsDao;
import io.renren.modules.work.entity.ScGoodsEntity;
import io.renren.modules.work.service.ScGoodsService;
import org.springframework.web.multipart.MultipartFile;


@Service("scGoodsService")
public class ScGoodsServiceImpl extends ServiceImpl<ScGoodsDao, ScGoodsEntity> implements ScGoodsService {
    @Autowired
    private ScGoodsDao scGoodsDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ScGoodsEntity> scGoodsEntityQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank((String) params.get("goodsname"))){
            scGoodsEntityQueryWrapper.like("goodsname",params.get("goodsname"));
        }
        IPage<ScGoodsEntity> page = this.page(
                new Query<ScGoodsEntity>().getPage(params),
                scGoodsEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public R importExcel(MultipartFile file) throws IOException {
        ExcelReader excelReader = null;
        InputStream inputStream = null;

            try {
                inputStream = file.getInputStream();
                excelReader = EasyExcel.read(inputStream, ExcelData_Goods.class,
                        new ExcelListener(scGoodsDao)).build();
                ReadSheet readSheet = EasyExcel.readSheet(0).build();
                excelReader.read(readSheet);

            } catch (IOException e) {
                e.printStackTrace();
                Log.error("import excel to db failed!",e);
            } finally {
                inputStream.close();
                // 这里一定别忘记关闭，读的时候会创建临时文件
                if (excelReader != null) {
                    excelReader.finish();
                }
            }
            Log.info("import excel to db successfully!");
        return R.ok();
    }

}